import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import axios from 'axios';
import { Repository } from 'typeorm';
import { Chat } from './entities/chat.entity';
import { parseRecord, stringifyRecord } from '../shared/utils';

@Injectable()
export class ChatService {
  constructor(
    @InjectRepository(Chat)
    private chatRepository: Repository<Chat>,
  ) {}

  private jsonKeys = ['links'];

  // 序列化
  private stringifyProperties(data: any) {
    return stringifyRecord(data, this.jsonKeys);
  }

  // 反序列化
  private parseProperties(data: any) {
    return parseRecord(data, this.jsonKeys);
  }

  // 对话大模型
  async chatModel(question: string) {
    try {
      const { data }: any = await axios({
        url: 'http://152.70.39.240:7779/search',
        method: 'POST',
        params: {
          question,
        },
      });
      // 目前api的解析
      if (data.judge == 'False') {
        return { content: '未检测到相关问题的图谱信息', triple: [] };
      } else if (data.judge == 'True') {
        const answer =
          (Array.isArray(data.answer) && data.answer.join('、')) || data.answer;
        return { content: answer, triple: data.triple || [] };
      }
    } catch (error) {
      throw new Error(error.message);
    }
  }

  // 获取聊天历史
  async getChatHistory(userId: number, targetUserId: number) {
    const records = await this.chatRepository.find({
      where: [
        { senderId: userId, receiverId: targetUserId },
        { senderId: targetUserId, receiverId: userId },
      ],
      order: { timestamp: 'ASC' }, // You may adjust the sorting order as needed
    });
    return { records: this.parseProperties(records) };
  }

  // 保存聊天记录
  async saveChat(
    senderId: number,
    receiverId: number,
    message: string,
    links: any = [],
  ): Promise<Chat> {
    const chat: any = this.chatRepository.create(
      this.stringifyProperties({
        senderId,
        receiverId,
        message,
        links,
      }),
    );
    return this.chatRepository.save(chat);
  }
}
